package com.sport.service;

import com.sport.constant.MessageConstant;
import com.sport.exception.BaseException;
import com.sport.exception.JudgeExistException;
import com.sport.mapper.JudgeMapper;
import com.sport.mapper.RoomMapper2;
import com.sport.pojo.dto.Referee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.sport.constant.MessageConstant.ROOM_INTO_ERROR;

@Service
public class JudgeServiceImpl implements JudgeService{
    @Autowired
    private JudgeMapper judgeMapper;
    @Autowired
    private RoomMapper2 roomMapper2;

    private Lock lock = new ReentrantLock();
    @Override
    @Transactional
    public int addJudge(Referee referee) {
        lock.lock();
        try{
            if(judgeMapper.isJudge(referee)!=0){
                throw new JudgeExistException(MessageConstant.JUDGE_EXIST);
            }
            int info = judgeMapper.addJudgeInUR(referee);
            int info2 = roomMapper2.addCurrentCount(referee.getRoomId());
            if(info==0 || info2==0){
                throw new BaseException("裁判加入失败");
            }
            if(roomMapper2.isFull(referee.getRoomId())==1){
                roomMapper2.updateRoomStatus(referee.getRoomId());
                return 2;
            }else {
                return 1;
            }
        }
        finally{
            lock.unlock();
        }

    }

    @Override
    public int start(String roomId) {
        if(roomMapper2.isFull(roomId)==0){
           return 2;
        }
        return judgeMapper.start(LocalDateTime.now(),roomId);
    }

    @Override
    @Transactional
    public int endGame(String roomId, String redScore, String blueScore) {
        int info,info2;
        if(Integer.parseInt(redScore)>Integer.parseInt(blueScore)){
            info = judgeMapper.updateEndGame(LocalDateTime.now(),roomId,0,redScore+":"+blueScore);
            info2 = judgeMapper.changeDao(1,roomId);
        }else if(Integer.parseInt(redScore)<Integer.parseInt(blueScore)){
            info = judgeMapper.updateEndGame(LocalDateTime.now(),roomId,1,redScore+":"+blueScore);
            info2 =judgeMapper.changeDao(0,roomId);
        }else {
            info = judgeMapper.updateEndGame(LocalDateTime.now(),roomId,2,redScore+":"+blueScore);
            info2 =judgeMapper.draw(roomId);
        }
        if(info==0 || info2==0){
            throw new BaseException("结束失败");
        }
         return info;
    }
}
